import { Injectable } from '@nestjs/common';
import { sum } from 'lodash';
import { PrismaService } from 'src/prisma/prisma.service';

@Injectable()
export class CalculatePointTowerService {
  constructor(private prisma: PrismaService) {}

  async calculate(args: Record<string, any>) {
    const { zoneId } = args;
    const zone = await this.prisma.zone.findFirst({
      where: { id: +zoneId },
      include: {
        towers: true,
        bets: true,
      },
    });

    const { towers, bets } = zone;

    // 删除数据库
    await this.prisma.pointTower.deleteMany({
      where: { tower: { zoneId: +zoneId } },
    });

    const pointTowerArr = towers.map((t, index) => {
      const betArr = bets
        .filter((_, b_index) => b_index < index)
        .map((b) => b.btSpan);
      const lei = sum(betArr);
      return {
        lei,
        x: lei,
        y: t.altitude,
        calcX: lei / 5,
        calcY: t.altitude * 2,
        towerId: t.id,
      };
    });

    await this.prisma.pointTower.createMany({ data: pointTowerArr });

    return pointTowerArr;
  }
}
